import Vue from 'vue'
import Vuex from 'vuex'
import { getToken, getUinfo, getPath, getRongToken, getCity, getCityCode } from './auth'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: getToken(),
    pl: 'H5',
    uifo: getUinfo(),
    path: getPath(),
    societyIndex: 0,
    cityName: getCity(),
    cityCode: getCityCode(),
    RongToken: getRongToken(),
    imHis: [],
    count: 0,
    imUser: null,
    config: {
      init: false // 微信初始化
    },
    wxAuth: window.localStorage.getItem('wxAuth') ? JSON.parse(window.localStorage.getItem('wxAuth')) : null // 微信的openid 和 access_token 相关信息
  },
  getters: {
    pl: state => state.pl,
    token: state => state.token,
    uifo: state => state.uifo,
    path: state => state.path,
    RongToken: state => state.RongToken,
    imHis: state => state.imHis,
    imUser: state => state.imUser,
    cityName: state => state.cityName,
    cityCode: state => state.cityCode
  },
  mutations: {
    SET_TOKEN (state, token) {
      state.token = token
    },
    SET_PL (state, pl) {
      state.pl = pl
    },
    SET_UINFO (state, uinfo) {
      state.uifo = uinfo
    },
    SET_PATH (state, path) {
      state.path = path
    },
    SET_SOCIETY_INDEX (state, societyIndex) {
      state.societyIndex = societyIndex
    },
    SET_RONG_TOKEN (state, RongToken) {
      state.RongToken = RongToken
    },
    SET_IMHIS: (state, list) => {
      state.count = 0
      state.imHis = list
      if (list.length) {
        let count = 0
        list.map(data => {
          count += data.unreadMessageCount
        })
        state.count = count
      }
    },
    SET_IMUSER: (state, user) => {
      state.imUser = user
    },
    SET_WX_CONFIG: (state, config) => {
      // 存储微信config
      state.config = Object.assign(state.config, config)
    },
    SET_WX_INIT: (state, value) => {
      state.config.init = value
    },
    SET_WXAUTH: (state, value) => {
      state.wxAuth = value
      window.localStorage.setItem('wxAuth', JSON.stringify(value))
    },
    SET_CITYNAME: (state, value) => {
      state.cityName = value
    },
    SET_CITYCODE: (state, value) => {
      state.cityCode = value
    }
  },
  actions: {
    setImHis ({ commit }, list) {
      return new Promise(resolve => {
        commit('SET_IMHIS', list)
        resolve()
      })
    }
  },
  modules: {
  }
})
